package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-09-04 10:10
 **/
@Slf4j // 获取日志对象
@RequestMapping("/depts")
@RestController
//@Scope("prototype") // 多例
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result selectDeptList() {
/*        Object loginUser = session.getAttribute("loginUser");
        if (loginUser==null){
            // 意味还没登录
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return Result.error("请先登录！");
        }*/
        System.out.println("selectDeptList" + deptService);
        log.info("查询全部部门");
        List<Dept> depts = deptService.list();
        return Result.success(depts);
    }

    @DeleteMapping
    public Result delDeptById(Integer id) {
        log.info("根据id删除部门:{}", id);
        deptService.delDeptById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getDeptById(@PathVariable Integer id) {
        System.out.println("selectDeptList" + deptService);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    /*
        前端传递的json类型后端需要实体类接收
        实体类必须包含json中存在的键
     */
    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        boolean flag = deptService.save(dept);
        if (flag) {
            log.info("添加部门成功");
            return Result.success();
        } else
            return Result.error("添加部门失败！");
    }

    @PutMapping
    public Result updateDeptById(@RequestBody Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        boolean flag = deptService.saveOrUpdate(dept);
        if (flag) {
//            System.out.println("修改部门成功");
            log.info("修改部门成功");
            return Result.success();
        } else
            return Result.error("修改部门失败！");
    }
}